﻿use sms
go
if exists(select name from sysobjects where name ='cp_mark_sendsuccess' and type = 'P')
drop procedure cp_mark_sendsuccess
go 
/****** Object:  StoredProcedure [dbo].[cp_mark_sendsuccess]    Script Date: 12/29/2010 15:27:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--发送成功时调用
create procedure [dbo].[cp_mark_sendsuccess]
@id int, --发送失败的ID，更改状态
@messageID nvarchar(24) --只有发送成功才返回一个MessageID，要改变
as
declare @state int
--查询传入ID的Message当前Stat
select @state = [State] from [Message] where ID=@id
--当状态为正在发送时
if(@state & 0xf0 = 0x10)
	begin
		--修改为发送成功
		update [Message] set [State]= @state | 0x30,ModifyTime=getdate() where ID=@id
		--再查找同一批次的短信状态是否一致
		declare @counts int, @batchid int
		select @batchid = [BatchID] from [Message] where ID=@id
		select @counts = COUNT(*) from [Message] where BatchID = @batchid
		--state = '正在发送' or state = '待发送'
		and ([State] & 0xf0 = 0x10 or [State] & 0xf0 = 0x00)
		--如果为0则返回同一批次(BatchID)的记录
		if(@counts = 0)
			begin
				declare @cou int
				select @cou = count(*) from [message] where state & 0xf0 = 0x20 and BatchID = @batchid
					if(@cou > 0)
						begin
							select * from [message] where BatchID = @batchid
						end
					else
						begin
							select * from [message] where ID = -1
						end
			end
		else
			begin
				select * from [message] where ID = -1
			end
	end
--如果为待发送
else
	begin
		if(len(@messageID) != 0)
			begin
			print @messageID
				--修改为正在发送，并加上MessageID
				update [Message] set [State]= @state | 0x10,MessageId = @messageID,ModifyTime=getdate() where ID=@id
			end
			select * from [message] where ID = -1
	end
